const {mysql} = require('../../qcloud')

// 获取收货地址列表（ addressselect/index.vue/getAddressList 方法）
async function getListAction(ctx) {
  	const openId = ctx.query.openId
  	const addressList = await mysql('nideshop_address').where({
    	'user_id': openId
  	}).orderBy('is_default', 'desc').select()
  	ctx.state.data = {
    	addressList
  	}
}

// 获取详细地址（goods/goods.vue/goodsDetail 方法）
async function detailAction(ctx) {
  	const id = ctx.query.id
  	const detailData = await mysql('nideshop_address').where({
    	'id': id
  	}).select()
  	ctx.state.data = {
    	detailDatas:detailData[0]
  	}
}

// 添加或更新收货地址（addAddress/index.vue/saveAddress 方法）
async function saveAction(ctx) {
  	const addressId = ctx.request.body.addressId
  	const { userName, telNumber, address, detailaddress, checked, openId } = ctx.request.body
  	// 如果前端传checked有值时，查询数据库中是否有默认地址，如果有，将is_default值改为0
  	if (checked) {
    	const isDefault = await mysql('nideshop_address').where({
      	'user_id': openId,
      	'is_default': 1
    	}).select()
    	//如果有默认地址
    	if (isDefault.length > 0) {
      		await mysql('nideshop_address').where({
        		'user_id': openId,
        		'is_default': 1
      		}).update({
        		'is_default': 0
      		})
    	}
  	}
  	//如果前端传过来的地址id为空
  	if (!addressId) {
    	// 添加地址
    	const data = await mysql('nideshop_address').insert({
      		name: userName,
      		mobile: telNumber,
      		address: address,
      		address_detail: detailaddress,
      		user_id: openId,
      		// 如果checked的状态为true，或checked存在，则将is_default设为1
      		is_default: checked == 'true' || checked ? 1 : 0
    	})
    	if (data) {
      		ctx.state= {
        	data: "新建地址添加成功"
      		}
    	} else {
      		ctx.state = {
        		data: "新建地址添加失败"
      		}
    	}
  	} else {
  		//如果前端传过来有地址id时
    	// 更新地址
    	const data = await mysql('nideshop_address').where({
      		'id': addressId
    	}).update({
      		name: userName,
      		mobile: telNumber,
      		address: address,
      		address_detail: detailaddress,
      		user_id: openId,
      		is_default: checked == 'true' || checked ? 1 : 0
    	})
    	if (data) {
      		ctx.state = {
       			data: "地址修改成功"
      		}
    	} else {
      		ctx.state = {
        		data: "地址修改失败"
      		}
    	}	
  	}
}

//删除地址（ addAddress/index.vue/deladress 方法）
async function delAdress(ctx){
	const {openId,addressId} = ctx.request.body
	// console.log("删除",openId,addressId)
  if(addressId){
    const deldata = await mysql('nideshop_address').where({
      'user_id':openId,
      'id':addressId
    }).del()
    if (deldata) {
      ctx.state = {
        data:true
      }
    }else{
      ctx.state = {
        data:false
      }
    }
  }else{
    ctx.state = {
      data:false
    }
  }	
}

module.exports = {
  getListAction,
  detailAction,
  saveAction,
  delAdress
}